package com.demon.auto.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.demon.auto.handle.SignWebSocketHandler;
import com.demon.auto.model.ApiResponseModel;
import com.demon.auto.model.dto.ClientConfigDto;
import com.demon.auto.model.dto.SignClientDto;
import com.demon.auto.model.entity.SignClientEntity;
import com.demon.auto.scheduler.DynamicTaskScheduler;
import com.demon.auto.service.SignClientService;
import com.demon.auto.utils.LocalDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 签到业务
 *
 * @author huangrz
 * @version 1.0
 * @date 2025/02/17 14:14
 */
@RequestMapping("/api/sign")
@RestController
public class SignController {

    @Autowired
    private SignClientService signClientService;

    @Autowired
    private DynamicTaskScheduler dynamicTaskScheduler;

    @Autowired
    private SignWebSocketHandler signWebSocketHandler;


    /**
     * 执行签到
     *
     * @param clientName 客户端名称
     * @return ResponseEntity<Boolean>
     */
    @RequestMapping("/execSign")
    public ApiResponseModel<Long> execSign(String clientName) {
        if (StringUtils.isBlank(clientName)) {
            return ApiResponseModel.error("客户端名称不能为空", null);
        }
        SignClientDto client = signClientService.getSignClientByClientName(clientName);
        if (client == null) {
            return ApiResponseModel.error("客户端不存在", null);
        }
        Map<String, Object> result = signWebSocketHandler.executeSignIn(client);
        Long signRecordId = result.get("signRecordId") == null ? null : (Long) result.get("signRecordId");
        return ApiResponseModel.ok(result.get("msg").toString(), signRecordId);
    }

    /**
     * 忽略当天签到
     *
     * @param clientName 客户端名称
     * @return ResponseEntity<Boolean>
     */
    @RequestMapping("/ignoreTodaySign")
    public ApiResponseModel<Boolean> ignoreTodaySign(String clientName) {
        if (StringUtils.isBlank(clientName)) {
            return ApiResponseModel.error("客户端名称不能为空", false);
        }
        SignClientDto client = signClientService.getSignClientByClientName(clientName);
        if (client == null) {
            return ApiResponseModel.error("客户端不存在", false);
        }
        ClientConfigDto config = client.getConfig();
        if (config == null) {
            return ApiResponseModel.error("客户端配置为空", false);
        }

        List<String> ignoreDateList = config.getIgnoreDateList();
        if (ignoreDateList == null) {
            ignoreDateList = new ArrayList<>();
        }
        LocalDate now = LocalDate.now();
        // 添加忽略时间
        ignoreDateList.add(LocalDateUtil.formatLocalDate(now));
        // 移除早于当天的时间
        ignoreDateList = ignoreDateList.stream()
                .map(LocalDateUtil::parserLocalDate)
                .filter(date -> !date.isBefore(now))
                .map(LocalDateUtil::formatLocalDate)
                .distinct()
                .collect(Collectors.toList());

        config.setIgnoreDateList(ignoreDateList);
        LambdaUpdateWrapper<SignClientEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SignClientEntity::getClientName, clientName)
                .set(SignClientEntity::getConfigJson, JSON.toJSONString(config));
        boolean flag = signClientService.update(updateWrapper);
        if (flag) {
            // 取消任务
            dynamicTaskScheduler.cancelClientTask(clientName);
        }
        return ApiResponseModel.ok("已忽略当天签到", flag);
    }

    /**
     * 关闭客户端连接
     *
     * @param clientName 客户端名称
     * @return ResponseEntity<Boolean>
     */
    @RequestMapping("/disconnectClient")
    public ApiResponseModel<Boolean> disconnectClient(String clientName) {
        if (StringUtils.isBlank(clientName)) {
            return ApiResponseModel.error("客户端名称不能为空", false);
        }
        SignClientDto client = signClientService.getSignClientByClientName(clientName);
        if (client == null || client.getConfig() == null) {
            return ApiResponseModel.error("客户端不存在或客户端配置为空", false);
        }
        return ApiResponseModel.ok("关闭客户端连接", signWebSocketHandler.removeClientWebsocket(clientName, "API请求关闭客户端连接"));
    }

}
